package controllers

import javax.inject.Inject
import play.api.mvc._
import dao._
import models.Tables._
import play.api.libs.json.Json
import play.api.data.Form
import play.api.data.Forms._
import tool.FormTool
import utils.Utils

import scala.concurrent.ExecutionContext.Implicits.global

case class RegionData(chr: String, start: Int, end: Int)


class GenomeSearchController @Inject()(cc:ControllerComponents,bgAnnoDao: BgAnnoDao) extends AbstractController(cc) {

  val regionForm = Form(
    mapping(
      "chr" -> text,
      "start" -> number,
      "end" -> number
    )(RegionData.apply)(RegionData.unapply)
  )

  def searchByGeneIdBefore = Action {
    Ok(views.html.genome.search.searchByGeneId())
  }

  def searchByRegionBefore = Action {
    Ok(views.html.genome.search.searchByRegion())
  }

  def getAllGeneIds = Action.async {
    bgAnnoDao.selectAllGeneIds.map { x =>
      Ok(Json.toJson(x))
    }
  }

  def getAllChrs = Action.async {
    bgAnnoDao.selectAllChrs.map { x =>
      Ok(Json.toJson(x))
    }
  }

  def searchByGeneId = Action.async { implicit request =>
    val data = FormTool.geneIdForm.bindFromRequest.get
    val geneIds = data.geneId.split(",").distinct
    bgAnnoDao.selectByGeneIds(geneIds).map { x =>
      val array = Utils.getJsonByTs(x)
      Ok(Json.toJson(array))
    }
  }

  def searchByRegion = Action.async { implicit request =>
    val data = regionForm.bindFromRequest.get
    bgAnnoDao.selectByRegionData(data).map { x =>
      val array = Utils.getJsonByTs(x)
      Ok(Json.toJson(array))
    }
  }

}
